<template>
  <div class="my-courses-container">
    <div class="header">
      <h2>我的课程</h2>
      <div class="actions">
        <el-button type="primary" @click="goToCreateCourse">
          <el-icon><Plus /></el-icon> 创建课程
        </el-button>
        
        <div class="view-toggle">
          <el-tooltip content="卡片视图" placement="top">
            <el-button 
              :type="viewMode === 'card' ? 'primary' : ''" 
              @click="viewMode = 'card'"
              :icon="Grid"
            />
          </el-tooltip>
          <el-tooltip content="列表视图" placement="top">
            <el-button 
              :type="viewMode === 'list' ? 'primary' : ''" 
              @click="viewMode = 'list'"
              :icon="List"
            />
          </el-tooltip>
        </div>
      </div>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="6" animated />
    </div>

    <div v-else>
      <!-- 卡片视图 -->
      <div v-if="viewMode === 'card' && courses.length > 0" class="courses-grid">
        <el-card 
          v-for="course in courses" 
          :key="course.id" 
          class="course-card"
          shadow="hover"
        >
          <div class="course-image-container">
            <img :src="getCourseImage(course.couPic)" class="course-image" alt="课程封面">
          </div>
          <div class="course-content">
            <h3 class="course-title">{{ course.couName }}</h3>
            <p class="course-intro">{{ course.couIntroduction || '暂无课程简介' }}</p>
            
            <div class="course-meta">
              <div class="course-stats">
                <span class="stat-item">
                  <el-icon><View /></el-icon> {{ course.clicks || 0 }}
                </span>
              </div>
              <el-tag :type="course.couPrice === 0 ? 'success' : 'warning'" size="small">
                {{ course.couPrice === 0 ? '免费' : `¥${course.couPrice}` }}
              </el-tag>
            </div>
          </div>
          
          <div class="course-actions">
            <el-tooltip content="课程详情" placement="top">
              <el-button 
                type="primary" 
                size="small" 
                @click="goToCourseDetail(course.id)"
                :icon="Document"
              />
            </el-tooltip>
            <el-tooltip content="编辑课程" placement="top">
              <el-button 
                type="primary" 
                size="small" 
                @click="openEditDialog(course)"
                :icon="Edit"
              />
            </el-tooltip>
            <el-tooltip content="章节管理" placement="top">
              <el-button 
                type="info" 
                size="small" 
                @click="goToChapterManagement(course.id)"
                :icon="Folder"
              />
            </el-tooltip>
            <el-tooltip content="删除课程" placement="top">
              <el-button 
                type="danger" 
                size="small" 
                @click="confirmDeleteCourse(course.id)"
                :icon="Delete"
              />
            </el-tooltip>
          </div>
        </el-card>
      </div>
      
      <!-- 列表视图 -->
      <div v-else-if="viewMode === 'list' && courses.length > 0" class="courses-list">
        <el-table :data="courses" style="width: 100%">
          <el-table-column label="课程封面" width="120">
            <template #default="{ row }">
              <img 
                :src="getCourseImage(row.couPic)" 
                class="course-thumbnail" 
                alt="课程封面"
              >
            </template>
          </el-table-column>
          <el-table-column prop="couName" label="课程名称" width="180" />
          <el-table-column prop="couIntroduction" label="课程简介" show-overflow-tooltip />
          <el-table-column label="浏览量" width="100">
            <template #default="{ row }">
              <el-tag size="small">
                <el-icon><View /></el-icon> {{ row.clicks || 0 }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="价格" width="100">
            <template #default="{ row }">
              <el-tag :type="row.couPrice === 0 ? 'success' : 'warning'" size="small">
                {{ row.couPrice === 0 ? '免费' : `¥${row.couPrice}` }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220">
            <template #default="{ row }">
              <el-tooltip content="课程详情" placement="top">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="goToCourseDetail(row.id)"
                  :icon="Document"
                />
              </el-tooltip>
              <el-tooltip content="编辑课程" placement="top">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="openEditDialog(row)"
                  :icon="Edit"
                />
              </el-tooltip>
              <el-tooltip content="章节管理" placement="top">
                <el-button 
                  type="info" 
                  size="small" 
                  @click="goToChapterManagement(row.id)"
                  :icon="Folder"
                />
              </el-tooltip>
              <el-tooltip content="删除课程" placement="top">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="confirmDeleteCourse(row.id)"
                  :icon="Delete"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <el-empty v-else description="您还没有创建任何课程" />
    </div>

    <!-- 编辑课程对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      :title="`编辑课程 - ${currentCourse.couName}`" 
      width="500px"
    >
      <el-form :model="currentCourse" label-width="80px">
        <el-form-item label="课程名称">
          <el-input v-model="currentCourse.couName" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程简介">
          <el-input 
            v-model="currentCourse.couIntroduction" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入课程简介" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditCourse">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, 
  View, 
  Plus, 
  Grid, 
  List, 
  Document, 
  Edit, 
  Folder, 
  Delete 
} from '@element-plus/icons-vue'
import { teacherApi } from '@/api/teacher'
import { courseApi } from '@/api/course'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

const loading = ref(false)
const courses = ref([])
const teacherId = ref(null)
const viewMode = ref('card')
const defaultCourseImage = ref(require('@/assets/fault.png'))
const editDialogVisible = ref(false)
const currentCourse = ref({
  id: '',
  couName: '',
  couIntroduction: ''
})

// 获取课程图片
const getCourseImage = (imageUrl) => {
  return imageUrl || defaultCourseImage.value
}

// 获取教师ID
const fetchTeacherId = async () => {
  try {
    if (!authStore.userId) {
      throw new Error('用户ID不存在')
    }

    const response = await teacherApi.getTeacherByUid(authStore.userId)
    const teacherData = response.data || response
    
    if (!teacherData) {
      throw new Error('教师信息不存在')
    }
    
    if (!teacherData.id) {
      throw new Error('教师ID不存在')
    }
    
    teacherId.value = teacherData.id
    return teacherId.value
  } catch (error) {
    ElMessage.error('获取教师信息失败: ' + error.message)
    return null
  }
}

// 获取教师课程
const fetchCourses = async () => {
  try {
    loading.value = true
    const tid = await fetchTeacherId()
    
    if (!tid) {
      courses.value = []
      return
    }
    
    const response = await teacherApi.getTeacherCourses(tid)
    courses.value = Array.isArray(response) ? response : 
                   Array.isArray(response?.data) ? response.data : []
    
    if (courses.value.length === 0) {
      ElMessage.info('您还没有创建任何课程')
    }
  } catch (error) {
    ElMessage.error('获取课程列表失败: ' + error.message)
    courses.value = []
  } finally {
    loading.value = false
  }
}

// 打开编辑对话框
const openEditDialog = (course) => {
  currentCourse.value = {
    id: course.id,
    couName: course.couName,
    couIntroduction: course.couIntroduction || ''
  }
  editDialogVisible.value = true
}

// 处理编辑课程
const handleEditCourse = async () => {
  try {
    if (!currentCourse.value.couName.trim()) {
      ElMessage.warning('请输入课程名称')
      return
    }

    const { id, couName, couIntroduction } = currentCourse.value
    await courseApi.updateCourseInfo(id, {
      couName,
      couIntroduction
    })
    
    ElMessage.success('课程更新成功')
    editDialogVisible.value = false
    await fetchCourses() // 刷新列表
  } catch (error) {
    ElMessage.error('更新课程失败: ' + error.message)
  }
}

// 跳转到课程详情页面
const goToCourseDetail = (courseId) => {
  router.push(`/course/detail/${courseId}`)
}

// 跳转到创建课程页面
const goToCreateCourse = () => {
  router.push('/course/create')
}

// 跳转到章节管理页面
const goToChapterManagement = (courseId) => {
  router.push(`/course/chapter/${courseId}`)
}

// 确认删除课程
const confirmDeleteCourse = (courseId) => {
  ElMessageBox.confirm(
    '确定要删除这个课程吗？删除后将无法恢复！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await courseApi.deleteCourse(courseId)
      ElMessage.success('删除成功')
      await fetchCourses() // 刷新列表
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 初始化加载数据
onMounted(() => {
  fetchCourses()
})
</script>

<style scoped>
.my-courses-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header h2 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.view-toggle {
  display: flex;
  gap: 5px;
  margin-left: 10px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
}

.view-toggle .el-button {
  border-radius: 0;
  border: none;
}

.loading-container {
  padding: 20px;
}

.courses-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  padding: 10px;
}

.course-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  border-radius: 8px;
  overflow: hidden;
}

.course-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.course-image-container {
  height: 140px;
  overflow: hidden;
  background-color: #f5f7fa;
}

.course-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.course-thumbnail {
  width: 80px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.course-card:hover .course-image {
  transform: scale(1.05);
}

.course-content {
  padding: 12px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.course-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.course-intro {
  color: #606266;
  font-size: 13px;
  line-height: 1.4;
  height: 55px;
  margin: 0 0 12px 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.course-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.course-stats {
  display: flex;
  gap: 10px;
}

.stat-item {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 12px;
}

.stat-item .el-icon {
  margin-right: 4px;
  font-size: 13px;
}

.course-actions {
  padding: 0 12px 12px;
  display: flex;
  justify-content: space-between;
  gap: 6px;
}

.course-actions .el-button {
  flex: 1;
  min-width: 0;
}

.courses-list {
  margin-top: 20px;
}

.el-table .el-button {
  margin: 0 3px;
}
</style>